

import subprocess

from ErrorHandler import ErrorSysGPG

class _OFile:
    def ENCRYPT_FILE(self, file_path: str, data: bytes) -> bytes:
        data_encrypt = self.ENCRYPT(data)
        
        if data_encrypt:
            with open(file_path, 'wb') as file:
                file.write( data_encrypt )
            
    def DECRYPT_FILE(self, file_path: str) -> bytes:
        with open(file_path, 'rb') as file:
            return self.DECRYPT(file.read())


class GPG(_OFile):
    def __init__(self, gpg_id: str):
        self.gpg_id = gpg_id
        
    def ENCRYPT(self, data: bytes) -> bytes:
        use_gpg = subprocess.Popen( ['gpg', '-r', f'{self.gpg_id}', f'-eq'],
                                    stdin=subprocess.PIPE,
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE
                                    )
        
        output_data, error = use_gpg.communicate(input=data)
        
        if not error:
            return output_data
        else:
            raise ErrorSysGPG( error.decode() )
        
    def DECRYPT(self, data: bytes) -> bytes:
        use_gpg = subprocess.Popen( ['gpg', '-r', f'{self.gpg_id}', f'-dq'],
                                    stdin=subprocess.PIPE,
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE
                                    )
        
        output_data, error = use_gpg.communicate(input=data)
        
        if not error:
            return output_data
        else:
            raise ErrorSysGPG( error.decode() )


class GPG_SYM(_OFile):
    def ENCRYPT(self, data: bytes) -> bytes:
        use_gpg = subprocess.Popen( ['gpg', '-c', '--cipher-algo', 'AES256'],
                                    stdin=subprocess.PIPE,
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE
                                    )
        
        output_data, error = use_gpg.communicate(input=data)
        
        if not error:
            return output_data
        else:
            raise ErrorSysGPG( error.decode() )
        
    def DECRYPT(self, data: bytes) -> bytes:
        use_gpg = subprocess.Popen( ['gpg', '-dq'],
                                    stdin=subprocess.PIPE,
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE
                                    )
        
        output_data, error = use_gpg.communicate(input=data)
        
        if not error:
            return output_data
        else:
            raise ErrorSysGPG( error.decode() )



